package com.party.jackclientandroid.ui_mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.MyAttentionService;
import com.party.jackclientandroid.api.ShopService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.MyAttention;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.loadviewhelper.help.OnLoadViewListener;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.ShopDetailActivity;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.view.dialog.ConfirmDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

//我的关注
public class AttentionListActivity extends BaseActivityTitle {
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    List<MyAttention> dataList = new ArrayList<>();
    CommonAdapter<MyAttention> commonAdapter;
    int page = 1;
    ShopService shopService;
    MyAttentionService myAttentionService;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attention_list);
        initData();
        initListener();
    }

    protected void initData() {
        setMiddleText("关注");
        helper = new LoadViewHelper(mRefreshLayout);
        helper.setListener(new OnLoadViewListener() {
            @Override
            public void onRetryClick() {
                getNeedData();
            }
        });
        shopService = new ShopService(this);
        myAttentionService = new MyAttentionService(this);
        mRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        commonAdapter = new CommonAdapter<MyAttention>(mActivity, R.layout.item_my_attention, dataList) {
            @Override
            protected void convert(ViewHolder viewHolder, final MyAttention item, int position) {
                viewHolder.setText(R.id.shop_name_tv, item.getShopName());
                viewHolder.setText(R.id.street_address_tv, item.getSymbolBuild());
                Button btn = viewHolder.getView(R.id.attention_btn);
                btn.setTextColor(getResources().getColor(R.color.black));
                btn.setText("已关注");
                btn.setBackground(getResources().getDrawable(R.drawable.attention_bg_btn_normal));
                Glide.with(mActivity).load(item.getHomeImg()).into((ImageView) viewHolder.getView(R.id.shop_image_iv));
                ((Button) viewHolder.getView(R.id.attention_btn)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View view) {
                        if (item.isAttention()) {
                            DialogController.showConfirmDialog(mActivity, "你确定要取消关注？", new ConfirmDialog.DialogListener() {
                                @Override
                                public void cancel(ConfirmDialog dialog) {
                                    dialog.dismiss();
                                }

                                @Override
                                public void ok(ConfirmDialog dialog) {
                                    dialog.dismiss();
                                    cancelAttention(item.getId(), (Button) view, item);
                                }
                            });
                        } else {
                            addAttention(item.getId() + "", (Button) view, item);
                        }
                    }
                });
            }
        };
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.layout_divider_item_decoration));
        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setAdapter(commonAdapter);

        helper.showLoading();
        getNeedData();
    }

    protected void initListener() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                handleItemClick(position);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getNeedData();
            }
        });
    }


    /**
     * item点击事件
     *
     * @param position
     */
    private void handleItemClick(int position) {
        mActivity.startActivity(ShopDetailActivity.class,"shopId", dataList.get(position).getId()+"");
    }

    /**
     * 下拉获取数据
     */
    public void getNeedData() {
        page = 1;
        addDisposableIoMain(myAttentionService.getUserAttentionShopList(page, Constant.PAGE_SIZE), new DefaultConsumer<List<MyAttention>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<MyAttention>> baseBean) {
                dataList.clear();
                if (baseBean.getData() != null && baseBean.getData().size() > 0) {
                    dataList.addAll(baseBean.getData());
                }
                commonAdapter.notifyDataSetChanged();
                mRefreshLayout.finishRefresh();
                if (baseBean.getData().size() < Constant.PAGE_SIZE) {
                    mRefreshLayout.setEnableLoadMore(false);
                }
                if (baseBean.getData().size() <= 0) {
                    helper.showEmpty();
                } else {
                    helper.showContent();
                }
            }
        });
    }

    /**
     * 加载更多
     */
    private void loadMoreData() {
        page++;
        addDisposableIoMain(myAttentionService.getUserAttentionShopList(page, Constant.PAGE_SIZE), new DefaultConsumer<List<MyAttention>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<MyAttention>> baseBean) {
                List<MyAttention> data = baseBean.getData();
                boolean noMoreData = false;
                if (data != null && data.size() > 0) {
                    dataList.addAll(data);
                    if (data.size() <= ConstUtils.PAGE_SIZE) {
                        noMoreData = true;
                    }
                } else {
                    noMoreData = true;
                }
                commonAdapter.notifyDataSetChanged();
                // 没有更多数据了
                if (noMoreData) {
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    mRefreshLayout.finishLoadMore();
                }
            }
        });
    }

    //取消关注
    private void cancelAttention(String shopId, final Button btn, final MyAttention myAttention) {
        addDisposableIoMain(shopService.cancelAttention(shopId), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> baseBean) {
                btn.setText("关注");
                btn.setTextColor(getResources().getColor(R.color.color_ffb00f));
                btn.setBackground(getResources().getDrawable(R.drawable.attention_bg_btn_selected));
                myAttention.setAttention(false);
            }
        });
    }

    //关注
    private void addAttention(String shopId, final Button btn, final MyAttention myAttention) {
        addDisposableIoMain(shopService.addAttention(shopId), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> baseBean) {
                btn.setText("已关注");
                btn.setTextColor(getResources().getColor(R.color.black));
                btn.setBackground(getResources().getDrawable(R.drawable.attention_bg_btn_normal));
                myAttention.setAttention(true);
            }
        });
    }
}
